<template>
  <HeaderComponent />
  <!--顶部个人信息界面-->
  <div class="profile-container">
    <div class="cover-photo">
      <img
        :src="userinfo.bg || '/assets/bg/default.jpg'"
        style="width: 100%; height: 400px; object-fit: cover"
      />
      <el-button
        v-if="!userid"
        type="info"
        class="edit-cover-btn"
        style="color: #000"
        size="large"
        @click="editCover"
      >
        <el-icon><Camera /></el-icon> 编辑封面照片
      </el-button>
      <input
        type="file"
        id="fileInput"
        ref="fileInput"
        style="display: none"
        accept="image/*"
      />
    </div>
    <!-- 个人信息和功能按钮区域 -->
    <div class="profile-info">
      <!-- 左侧个人信息 -->
      <div class="left-info">
        <div class="avatar-container">
          <img
            class="avatar"
            :src="userinfo.avatar || '/assets/avatar/default.jpg'"
            @click="handleAvatarClick"
          />
          <!-- 添加文件输入框和上传按钮 -->
          <input
            type="file"
            id="imageInput"
            accept="image/*"
            ref="imageInput"
            style="display: none"
          />
          <el-icon class="edit-avatar-icon"><Camera /></el-icon>
        </div>
        <div class="name-and-friends">
          <h2 class="name">{{ userinfo.username }}</h2>
          <p class="friends">{{ userinfo.contact?.length || 0 }} 位关注</p>
        </div>
      </div>
      <!-- 右侧功能按钮 -->
      <div class="right-buttons" v-if="!userid">
        <el-button class="edit-profile-btn" size="large" @click="edit">
          <el-icon><Edit /></el-icon> 编辑资料
        </el-button>
      </div>
      <div class="right-buttons" v-if="userid">
        <el-button
          class="edit-profile-btn"
          size="large"
          :type="
            LoginUser.contact && LoginUser.contact.includes(userinfo.id)
              ? 'danger'
              : 'primary'
          "
          @click="
            addContact(
              LoginUser.contact ? (LoginUser.contact.includes(userinfo.id) ? 1 : 0) : 0
            )
          "
        >
          {{ ConatctStatus }}
        </el-button>
      </div>
    </div>
  </div>
  <!--内容界面-->
  <div class="main">
    <div class="main-contan">
      <el-row :gutter="20">
        <!-- 左侧区域 -->
        <el-col :span="16">
          <div class="left-card">
            <!-- 使用 ArticleCard 组件替换原有动态发布和展示区域 -->
            <ArticleCard
              :articles="articles"
              :NewArticle="user.id == userinfo.id"
              v-if="articles.length > 0"
            />
            <span v-if="articles.length == 0" class="neon-text"> 该用户未发布动态 </span>
          </div>
        </el-col>
        <!-- 右侧区域 -->
        <el-col :span="8">
          <el-card class="right-card">
            <!-- 右侧内容 -->
            <div class="right-content">
              <span style="font-size: 24px; font-weight: bold">个人资料</span>
              <div class="signature-section">
                <p class="signature-text">{{ userinfo.sign || "用户未填写" }}</p>
              </div>
              <div class="right-section">
                <el-icon class="section-icon"><User /></el-icon>
                <span>{{ userinfo.sex || "未填写" }}</span>
              </div>
              <div class="right-section">
                <el-icon class="section-icon"><Clock /></el-icon>
                <span>{{ userinfo.born || "未填写" }}</span>
              </div>
              <div class="right-section">
                <el-icon class="section-icon"><HomeFilled /></el-icon>
                <span>{{ userinfo.from || "未填写" }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { Camera, Clock, User, HomeFilled, Edit } from "@element-plus/icons-vue";
import HeaderComponent from "../../components/HeaderComponent.vue";
import ArticleCard from "../../components/ArticleCard.vue";
import api from "../../utils/index.js";
import { useRoute, useRouter } from "vue-router";

import { ElMessage } from "element-plus";
import userStore from "../../store/index";

const route = useRoute();
const router = useRouter();

//登录用户信息
const userStoreInfo = userStore();
const user = userStoreInfo.getUser();
const LoginUser = reactive({});
//用户页面该用户的id
const userid = route.query.id;
const userinfo = reactive({});
//该用户的文章信息
const articles = ref([]);

//关注状态
const ConatctStatus = computed(() => {
  return LoginUser.contact && LoginUser.contact.includes(userinfo.id)
    ? "取消关注"
    : "关注";
});
// 获取用户信息和文章
const fetchData = async () => {
  try {
    // 获取登录用户信息
    const LoginUserResponse = await api.get(`/users?id=${user.id}`);
    Object.assign(LoginUser, LoginUserResponse.data[0]);

    // 获取该页面下用户信息和文章
    const userId = userid || user.id;
    const userResponse = await api.get(`/users?id=${userId}`);
    Object.assign(userinfo, userResponse.data[0]);

    const articleResponse = await api.get(`/articles?user_id=${userId}`);
    articles.value = articleResponse.data;
  } catch (error) {
    ElMessage.error("获取数据失败: " + error.message);
  }
};

// 编辑封面照片
const fileInput = ref(null);
const editCover = () => {
  fileInput.value.click();
};
const handleFileUpload = async () => {
  const file = fileInput.value.files[0];
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = async () => {
    const base64Image = reader.result;
    await api.patch(`/users/${userinfo.id}`, {
      bg: base64Image,
    });
    ElMessage.success("背景修改成功！");
    fetchData();
  };
};

// 点击头像时触发文件选择框
const imageInput = ref(null);
const handleAvatarClick = () => {
  if (imageInput.value) {
    imageInput.value.click();
  }
};
// 处理头像文件变更
const handleFileChange = () => {
  const file = imageInput.value.files[0];
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = async () => {
    const base64Image = reader.result;
    await api.patch(`/users/${userinfo.id}`, {
      avatar: base64Image,
    });
    ElMessage.success("头像修改成功！");
    fetchData();
  };
};

// 关注/取消关注操作
const addContact = async (status) => {
  try {
    if (status === 0) {
      // 关注操作：将用户 ID 添加到登录用户的 contact 中
      if (!LoginUser.contact) {
        LoginUser.contact = [];
      }
      if (!LoginUser.contact.includes(userinfo.id)) {
        LoginUser.contact.push(userinfo.id);
      }
    } else if (status === 1) {
      // 取消关注操作：从登录用户的 contact 中删除该用户 ID
      if (LoginUser.contact) {
        LoginUser.contact = LoginUser.contact.filter((id) => id !== userinfo.id);
      }
    }

    await api.patch(`/users/${LoginUser.id}`, { contact: LoginUser.contact });
    ElMessage.success(status === 0 ? "关注成功" : "已取消关注");
  } catch (error) {
    ElMessage.error(
      status === 0 ? "关注失败: " + error.message : "取消关注失败: " + error.message
    );
  }
};

// 组件挂载时初始化数据
onMounted(() => {
  fetchData();
  if (imageInput.value) {
    imageInput.value.addEventListener("change", handleFileChange);
  }
  if (fileInput.value) {
    fileInput.value.addEventListener("change", handleFileUpload);
  }
});

// 跳转到资料编辑页面
const edit = () => {
  router.push({ path: "/useredit" });
};
</script>

<style scoped>
.profile-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #000;
  border-bottom: 1px solid #f2f4f7;
  padding-bottom: 20px;
}

.cover-photo {
  position: relative;
  width: 100%;
  max-width: 1000px;
}

.edit-cover-btn {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 5px;
  padding: 5px 10px;
}

.profile-info {
  display: flex;
  justify-content: space-between;
  width: 100%;
  max-width: 980px;
  margin-top: -50px;
}

.left-info {
  display: flex;
  align-items: end;
}

.avatar-container {
  position: relative;
  margin-right: 20px;
}

.avatar {
  width: 150px;
  height: 150px;
  border: 5px solid #fff;
  border-radius: 50%;
  object-fit: cover;
}

.edit-avatar-icon {
  position: absolute;
  bottom: 0;
  right: 0;
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  padding: 5px;
}

.name-and-friends {
  text-align: left;
}

.name {
  margin: 0;
  font-size: 24px;
}

.friends {
  margin-top: 5px;
  color: #666;
  font-size: 16px;
}

.main-content {
  padding: 0 !important;
}

.right-buttons {
  display: flex;
  align-items: end;
}

.edit-profile-btn {
  margin-right: 10px;
}

.main {
  background-color: #f2f4f7;
  padding: 20px;
}

.main-contan {
  max-width: 1000px;
  margin: 0 auto;
}

.left-card,
.right-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.main-content {
  max-width: 1000px;
  margin: 0 auto;
  /* 修改背景颜色和整体背景一致 */
  background-color: #f5f7fa;
  /* 添加左右边距 */
  padding: 20px 100px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.post-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.post-card:hover {
  transform: translateY(-2px);
}

.post-show-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.post-show-card:hover {
  transform: translateY(-2px);
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.username {
  margin-left: 15px;
}
.time {
  color: #999;
  font-size: 12px;
  margin-left: 10px;
}
.post-input {
  width: 100%;
  margin-bottom: 5px;
}

.search-input:focus {
  outline: none;
  border-color: #409eff;
}

.post-content {
  text-align: left;
  margin: 0 0 16px;
  font-size: 15px;
  line-height: 1.6;
  color: #1c1e21;
}

.post-image {
  width: 100%;
  height: auto;
  border-radius: 12px;
  object-fit: cover;
}

.post-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e4e6eb;
  color: #65676b;
  font-size: 14px;
}

.post-actions {
  display: flex;
  justify-content: space-around;
  padding: 8px 0;
}

.post-actions .el-button {
  flex: 1;
  padding: 8px;
  border-radius: 8px;
  transition: background-color 0.2s ease;
}

.post-actions .el-button:hover {
  background-color: #f0f2f5;
}

.right-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.section-icon {
  margin-right: 5px;
  color: #909399;
}

.edit-details-btn,
.add-featured-btn {
  width: 100%;
  margin-top: 10px;
  background-color: #e4e7ed;
  border-radius: 5px;
  padding: 5px 10px;
}

.neon-text {
  font-size: 48px;
  display: block;
  text-align: center;
  font-weight: bold;
  color: #acacac9e;
}
</style>
